<template>
  <div class="parameter-config">
    <a-row :gutter="16">
      <!-- 左侧面板 - API列表 -->
      <a-col :span="8" class="api-list-col">
        <a-card title="API列表" :bordered="false" class="api-list-card">
          <div class="search-box">
            <a-input-search 
              v-model:value.trim="apiSearchTerm" 
              placeholder="搜索API..." 
              style="margin-bottom: 16px" 
            />
          </div>
          
          <div class="api-list-container">
            <a-collapse v-if="groupedApis.length > 0" v-model:activeKey="activeKeys" ghost>
              <template v-for="group in groupedApis" :key="group.tag">
                <a-collapse-panel :header="`${group.tag} (${group.apis.length})`">
                  <a-list
                    :data-source="group.apis"
                    :loading="apiListLoading"
                    item-layout="horizontal"
                  >
                    <template #renderItem="{ item }">
                      <a-list-item 
                        :class="['api-item', { active: selectedApi === item }]"
                        @click="selectApi(item)"
                      >
                        <a-list-item-meta>
                          <template #title>
                            <span class="path">{{ item.path }}</span>
                          </template>
                          <template #description>
                            <span class="method" :class="item.method">{{ item.method.toUpperCase() }}</span>
                            <span class="summary">{{ item.summary }}</span>
                          </template>
                        </a-list-item-meta>
                      </a-list-item>
                    </template>
                  </a-list>
                </a-collapse-panel>
              </template>
            </a-collapse>
            <div v-else>
              <a-list
                :data-source="filteredApis"
                :loading="apiListLoading"
                item-layout="horizontal"
              >
                <template #renderItem="{ item }">
                  <a-list-item 
                    :class="['api-item', { active: selectedApi === item }]"
                    @click="selectApi(item)"
                  >
                    <a-list-item-meta>
                      <template #title>
                        <span class="path">{{ item.path }}</span>
                      </template>
                      <template #description>
                        <span class="method" :class="item.method">{{ item.method.toUpperCase() }}</span>
                        <span class="summary">{{ item.summary }}</span>
                      </template>
                    </a-list-item-meta>
                  </a-list-item>
                </template>
                <template #footer>
                  <div v-if="filteredApis.length === 0" class="no-data">
                    <a-empty description="暂无匹配的API" />
                  </div>
                </template>
              </a-list>
            </div>
          </div>
        </a-card>
      </a-col>
      
      <!-- 右侧面板 - 参数详情 -->
      <a-col :span="16" class="param-detail-col">
        <a-card title="参数详情" :bordered="false" class="param-detail-card">
          <div v-if="selectedApi" class="api-detail">
            <a-descriptions :column="1" bordered>
              <a-descriptions-item label="接口路径">
                {{ selectedApi.path }}
              </a-descriptions-item>
              <a-descriptions-item label="请求方法">
                <span class="method" :class="selectedApi.method">
                  {{ selectedApi.method.toUpperCase() }}
                </span>
              </a-descriptions-item>
              <a-descriptions-item label="接口描述">
                {{ selectedApi.summary }}
              </a-descriptions-item>
              <a-descriptions-item label="所在分组">
                {{ selectedApi.tags }}
              </a-descriptions-item>
            </a-descriptions>
            
            <!-- 入参和出参展示 -->
            <div class="params-section">
              <a-tabs v-model:activeKey="activeTab">
                <a-tab-pane key="input" tab="入参 (Input Parameters)">
                  <a-table 
                    :columns="inputParamColumns" 
                    :data-source="inputParamData" 
                    :pagination="false"
                    :expand-row-by-click="true"
                    :row-key="record => record.key"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.dataIndex === 'name'">
                        <span :style="{ paddingLeft: `${record.level * 20}px` }">
                          {{ record.name }}
                        </span>
                      </template>
                      <template v-else-if="column.dataIndex === 'required'">
                        <span v-if="record.required" class="required">是</span>
                        <span v-else>否</span>
                      </template>
                    </template>
                  </a-table>
                </a-tab-pane>
                
                <a-tab-pane key="output" tab="出参 (Output Parameters)" force-render>
                  <a-table 
                    :columns="outputParamColumns" 
                    :data-source="outputParamData" 
                    :pagination="false"
                    :expand-row-by-click="true"
                    :row-key="record => record.key"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.dataIndex === 'name'">
                        <span :style="{ paddingLeft: `${record.level * 20}px` }">
                          {{ record.name }}
                        </span>
                      </template>
                      <template v-else-if="column.dataIndex === 'required'">
                        <span v-if="record.required" class="required">是</span>
                        <span v-else>否</span>
                      </template>
                    </template>
                  </a-table>
                </a-tab-pane>
              </a-tabs>
            </div>
          </div>
          
          <div v-else class="no-selection">
            <a-empty description="请从左侧API列表中选择一个接口" />
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, computed, watch, inject } from 'vue'
import { SwaggerUtils } from '../swaggerUtils'

// API URL
const apiSearchTerm = ref('')
const selectedApi = ref(null)
const apiList = ref([])
const swaggerData = ref(null)
const apiListLoading = ref(false)
const activeTab = ref('input')
const activeKeys = ref([])

// 参数信息
const inputParams = ref(null)
const outputParams = ref(null)

// 表格列定义
const inputParamColumns = [
  {
    title: '参数名',
    dataIndex: 'name',
    key: 'name',
    width: '40%'
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: '15%'
  },
  {
    title: '是否必填',
    dataIndex: 'required',
    key: 'required',
    width: '15%'
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description'
  }
]

const outputParamColumns = [
  {
    title: '参数名',
    dataIndex: 'name',
    key: 'name',
    width: '40%'
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: '15%'
  },
  {
    title: '是否必填',
    dataIndex: 'required',
    key: 'required',
    width: '15%'
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description'
  }
]

// 处理嵌套属性
function processNestedProperties(properties, prefix = '', level = 0, required = []) {
  if (!properties) return []
  
  let result = []
  Object.keys(properties).forEach(name => {
    const prop = properties[name]
    const fullName = prefix ? `${prefix}.${name}` : name
    
    // 添加当前属性
    result.push({
      key: fullName,
      name: name,
      type: prop.type || (prop.$ref ? 'object' : '未指定'),
      required: required.includes(name),
      description: prop.description || prop.title || '',
      level: level
    })
    
    // 特殊处理requestBody参数
    if (name === 'requestBody') {
      if (prop.type === 'array' && prop.items) {
        // 处理数组类型的requestBody
        const items = prop.items;
        if (items.type === 'object' && items.properties) {
          result = result.concat(
            processNestedProperties(items.properties, fullName, level + 1, items.required || [])
          )
        }
      } else if (prop.type === 'object' && prop.properties) {
        // 处理对象类型的requestBody
        result = result.concat(
          processNestedProperties(prop.properties, fullName, level + 1, prop.required || [])
        )
      } else if (prop.properties) {
        // 处理直接有properties的情况
        result = result.concat(
          processNestedProperties(prop.properties, fullName, level + 1, prop.required || [])
        )
      }
      // 处理完requestBody后直接返回，避免重复处理子属性
      return;
    }
    
    // 处理对象类型的嵌套属性
    if (prop.type === 'object' && prop.properties && name !== 'requestBody') {
      result = result.concat(
        processNestedProperties(prop.properties, fullName, level + 1, prop.required || [])
      )
    }
    
    // 处理数组类型的嵌套属性
    if (prop.type === 'array' && prop.items) {
      if (prop.items.type === 'object' && prop.items.properties) {
        result = result.concat(
          processNestedProperties(prop.items.properties, fullName, level + 1, prop.items.required || [])
        )
      }
    }
  })
  
  return result
}

// 表格数据
const inputParamData = computed(() => {
  if (!inputParams.value || !inputParams.value.properties) return []
  
  return processNestedProperties(
    inputParams.value.properties, 
    '', 
    0, 
    inputParams.value.required || []
  )
})

const outputParamData = computed(() => {
  if (!outputParams.value || !outputParams.value.properties) return []
  
  // 展示完整的响应结构，而不仅仅是data字段下的内容
  return processNestedProperties(
    outputParams.value.properties, 
    '', 
    0, 
    outputParams.value.required || []
  )
})

// 过滤API列表
const filteredApis = computed(() => {
  if (!apiSearchTerm.value) return apiList.value
  const term = apiSearchTerm.value.toLowerCase()
  return apiList.value.filter(api =>
    api.path.toLowerCase().includes(term) ||
    api.summary.toLowerCase().includes(term) ||
    api.tags.toLowerCase().includes(term)
  )
})

// 按标签分组的API列表
const groupedApis = computed(() => {
  if (apiSearchTerm.value) {
    // 搜索模式下不分组
    return []
  }
  
  const groups = {}
  apiList.value.forEach(api => {
    const tag = api.tags || '未分类'
    if (!groups[tag]) {
      groups[tag] = {
        tag,
        apis: []
      }
    }
    groups[tag].apis.push(api)
  })
  
  // 转换为数组并排序
  return Object.values(groups).sort((a, b) => a.tag.localeCompare(b.tag))
})

const apiState = inject('apiState')
watch(() => apiState.data, (value) => {
  if (value) {
    swaggerData.value = value
    loadApiDocs(value)
  }
}, {
  immediate: true
})

// 加载API文档
async function loadApiDocs(data) {
  try {
    apiListLoading.value = true
    swaggerData.value = data

    // 检查是否为 OpenAPI 3.0.1
    if (!data.openapi || !data.openapi.startsWith('3.')) {
      console.error('该文档不是 OpenAPI 3.0.1 格式')
      return
    }

    // 解析API列表
    const apis = []
    Object.keys(data.paths).forEach(path => {
      const pathData = data.paths[path]
      Object.keys(pathData).forEach(method => {
        const methodData = pathData[method]
        apis.push({
          path: path,
          method: method,
          summary: methodData.summary || methodData.description || '',
          tags: methodData.tags ? methodData.tags.join(', ') : '未分类'
        })
      })
    })

    apiList.value = apis
    if (apis.length > 0) {
      // 默认展开所有分组
      activeKeys.value = groupedApis.value.map(group => group.tag)
      // 默认选中第一个分组的第一个接口
      const firstGroup = groupedApis.value.length > 0 ? groupedApis.value[0] : null
      const defaultApi = firstGroup && firstGroup.apis.length > 0 ? firstGroup.apis[0] : apis[0]
      selectedApi.value = defaultApi
      extractParameters(defaultApi)
    }
    console.log(`成功加载 ${apis.length} 个API接口`)
  } catch (error) {
    console.error('加载API文档失败:', error)
  } finally {
    apiListLoading.value = false
  }
}

// 选择API
function selectApi(api) {
  selectedApi.value = api
  extractParameters(api)
}

// 提取参数信息
function extractParameters(api) {
  if (!swaggerData.value) return

  const pathData = swaggerData.value.paths[api.path]
  const method = pathData[api.method]

  // 使用SwaggerUtils提取入参和出参
  inputParams.value = SwaggerUtils.extractInputParams(method, swaggerData.value)
  outputParams.value = SwaggerUtils.extractOutputParams(method, swaggerData.value)
}
</script>

<style scoped>
.parameter-config {
  padding: 16px;
  height: 100%;
  overflow: hidden;
}

.api-list-card,
.param-detail-card {
  height: 100%;
}

.api-list-container {
  max-height: calc(100vh - 250px);
  overflow-y: auto;
  overflow-x: hidden;
}

.param-detail-card :deep(.ant-card-body) {
  max-height: calc(100vh - 170px);
  overflow-y: auto;
}

.api-item {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 4px;
}

.api-item:hover {
  background-color: #f5f5f5;
}

.api-item.active {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.method {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
  font-weight: bold;
  margin-right: 8px;
  text-transform: uppercase;
}

.method.get {
  background: linear-gradient(135deg, #28a745, #218838);
}

.method.post {
  background: linear-gradient(135deg, #ffa500, #ff8c00);
}

.method.put {
  background: linear-gradient(135deg, #007bff, #0069d9);
}

.method.delete {
  background: linear-gradient(135deg, #dc3545, #c82333);
}

.path {
  font-weight: 500;
}

.summary {
  font-size: 12px;
  color: #666;
}

.required {
  color: #ff4d4f;
  font-weight: bold;
}

.no-selection {
  text-align: center;
  padding: 40px 0;
}

:deep(.ant-tabs-content) {
  height: calc(100% - 54px);
  overflow-y: auto;
}

/* 滚动条样式优化 */
.api-list-container::-webkit-scrollbar,
.param-detail-card :deep(.ant-card-body)::-webkit-scrollbar,
:deep(.ant-tabs-content)::-webkit-scrollbar {
  width: 6px;
}

.api-list-container::-webkit-scrollbar-track,
.param-detail-card :deep(.ant-card-body)::-webkit-scrollbar-track,
:deep(.ant-tabs-content)::-webkit-scrollbar-track {
  background: rgba(240, 240, 240, 0.8);
  border-radius: 3px;
}

.api-list-container::-webkit-scrollbar-thumb,
.param-detail-card :deep(.ant-card-body)::-webkit-scrollbar-thumb,
:deep(.ant-tabs-content)::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.api-list-container::-webkit-scrollbar-thumb:hover,
.param-detail-card :deep(.ant-card-body)::-webkit-scrollbar-thumb:hover,
:deep(.ant-tabs-content)::-webkit-scrollbar-thumb:hover {
  background: #a0a4aa;
}

/* Collapse 样式调整 */
:deep(.ant-collapse-header) {
  font-weight: 500;
  padding: 12px 16px !important;
}

:deep(.ant-collapse-content-box) {
  padding: 0px !important;
}

:deep(.ant-list-items) {
  padding: 0 16px 16px 16px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .api-list-col {
    flex: 0 0 100%;
    max-width: 100%;
  }
  
  .param-detail-col {
    display: none;
  }
}
</style>